<template>
  <div class="message-drawer" :class="{ 'open': value }">
    <div class="drawer-mask" @click="closeDrawer"></div>
    <div class="drawer-content">
      <div class="drawer-header">
        <div class="drawer-title">消息中心</div>
        <div class="header-actions">
          <div class="batch-mode-toggle" @click="toggleBatchMode">
            {{ batchMode ? '完成' : '批量操作' }}
          </div>
          <div class="drawer-close" @click="closeDrawer">
            <i class="fas fa-times"></i>
          </div>
        </div>
      </div>
      
      <div class="message-tabs">
        <div 
          v-for="tab in tabs" 
          :key="tab.id"
          class="message-tab"
          :class="{ active: activeTab === tab.id }"
          @click="activeTab = tab.id"
        >
          {{ tab.name }}
          <span v-if="getUnreadCount(tab.id)" class="tab-badge">{{ getUnreadCount(tab.id) }}</span>
        </div>
      </div>
      
      <!-- 批量操作工具栏 -->
      <div v-if="batchMode" class="batch-actions">
        <div class="select-all" @click="toggleSelectAll">
          <i :class="isAllSelected ? 'fas fa-check-square' : 'far fa-square'"></i>
          <span>全选</span>
        </div>
        <div class="batch-action-btns">
          <button class="btn-read" @click="batchMarkRead">标为已读</button>
          <button class="btn-delete" @click="batchDelete">删除</button>
        </div>
      </div>
      
      <!-- 筛选组件 -->
      <div class="search-filters">
        <div class="filter-tags">
          <div class="filter-tag" 
               v-for="(value, key) in activeFilters" 
               :key="key"
               @click="removeFilter(key)">
            {{ getFilterLabel(key, value) }}
            <i class="fas fa-times"></i>
          </div>
        </div>
        
        <div class="filter-button" @click="toggleAdvancedSearch">
          <i class="fas fa-sliders-h"></i>
          <span>筛选</span>
        </div>
        
        <div class="advanced-search-panel" v-if="showAdvancedSearch">
          <div class="filter-group">
            <div class="filter-label">类别</div>
            <div class="filter-options">
              <div class="filter-checkbox" 
                   v-for="option in typeOptions" 
                   :key="option.value"
                   @click="toggleFilterOption('type', option.value)">
                <i :class="isFilterSelected('type', option.value) ? 'fas fa-check-square' : 'far fa-square'"></i>
                <span>{{ option.label }}</span>
              </div>
            </div>
          </div>
          
          <div class="filter-group">
            <div class="filter-label">时间范围</div>
            <div class="date-filters">
              <div class="date-option" 
                   v-for="option in dateOptions" 
                   :key="option.value"
                   :class="{ 'active': searchFilters.dateRange === option.value }"
                   @click="setFilter('dateRange', option.value)">
                {{ option.label }}
              </div>
            </div>
          </div>
          
          <div class="filter-actions">
            <button class="btn-reset" @click="resetSearchFilters">重置</button>
            <button class="btn-apply" @click="applySearchFilters">应用</button>
          </div>
        </div>
      </div>
      
      <div class="search-sort">
        <div class="sort-label">排序方式：</div>
        <div class="sort-options">
          <div class="sort-option" 
               v-for="option in sortOptions" 
               :key="option.value"
               :class="{ 'active': currentSort === option.value }"
               @click="setSortOption(option.value)">
            {{ option.label }}
            <i :class="getSortIcon(option.value)"></i>
          </div>
        </div>
      </div>
      
      <pull-refresh @refresh="refreshMessages">
        <div class="message-list" @scroll="handleScroll" ref="messageListRef">
          <template v-if="filteredMessages.length > 0">
            <div 
              v-for="(message, index) in filteredMessages" 
              :key="message.id"
              class="swipe-container"
              @touchstart="touchStart($event, index)"
              @touchmove="touchMove($event, index)"
              @touchend="touchEnd(index)"
            >
              <div 
                class="message-item"
                :class="{ 
                  'unread': !message.read,
                  'selected': isSelected(message.id),
                  'deleting': message.deleting,
                  'swiping': message.swiping
                }"
                :style="{ transform: `translateX(${swipeOffset[index] || 0}px)` }"
                @click="batchMode ? toggleSelect(message.id) : handleMessageClick(message)"
              >
                <!-- 选择框 -->
                <div class="select-box" v-if="batchMode" @click.stop="toggleSelect(message.id)">
                  <i :class="isSelected(message.id) ? 'fas fa-check-square' : 'far fa-square'"></i>
                </div>
                
                <!-- 左侧滑出菜单 -->
                <div class="swipe-action left" :style="getSwipeLeftStyle(index)">
                  <div class="action-btn read-btn" @click.stop="handleMarkRead(message)">
                    <i class="fas fa-envelope-open"></i>
                    已读
                  </div>
                </div>
                
                <!-- 消息内容 -->
                <div class="message-content" :style="getSwipeStyle(index)">
                  <div class="message-icon" :style="{ backgroundColor: getTypeColor(message.type) }">
                    <i :class="getTypeIcon(message.type)"></i>
                  </div>
                  <div class="message-body">
                    <div class="message-title">{{ message.title }}</div>
                    <div class="message-detail">{{ message.content }}</div>
                    <div class="message-time">{{ message.time }}</div>
                  </div>
                </div>
                
                <!-- 右侧滑出菜单 -->
                <div class="swipe-action right" :style="getSwipeRightStyle(index)">
                  <div class="action-btn delete-btn" @click.stop="handleDelete(message)">
                    <i class="fas fa-trash"></i>
                    删除
                  </div>
                </div>
              </div>
              <div class="action-buttons-container" :class="{ 'show-actions': showActions[index] }">
                <div class="action-btn read-btn" @click.stop="handleMarkRead(message)">
                  <i class="fas fa-envelope-open"></i>
                  <span>已读</span>
                </div>
                <div class="action-btn delete-btn" @click.stop="handleDelete(message)">
                  <i class="fas fa-trash"></i>
                  <span>删除</span>
                </div>
              </div>
            </div>
          </template>
          
          <div v-else-if="loading" class="loading-message">
            <i class="fas fa-spinner fa-spin"></i>
            <div>加载中...</div>
          </div>
          
          <div v-else class="empty-message">
            <i class="fas fa-inbox empty-icon"></i>
            <div class="empty-text">暂无消息</div>
          </div>
          
          <div v-if="hasMore && !loadingMore" class="loading-more">
            <div class="loading-indicator">
              <i class="fas fa-spinner fa-spin"></i>
              <span>加载更多...</span>
            </div>
          </div>
        </div>
      </pull-refresh>
      
      <div class="drawer-footer">
        <div class="footer-btn" @click="handleMarkAllRead">全部已读</div>
        <div class="footer-btn danger" @click="handleClearMessages">清空消息</div>
      </div>
    </div>
    
    <!-- 消息详情弹窗 -->
    <transition name="fade">
      <div class="message-detail-modal" v-if="showMessageDetail">
        <div class="modal-overlay" @click="closeMessageDetail"></div>
        <div class="modal-content">
          <div class="modal-header">
            <h3>{{ currentDetailMessage.title }}</h3>
            <i class="fas fa-times close-icon" @click="closeMessageDetail"></i>
          </div>
          <div class="modal-body">
            <div class="message-meta">
              <div class="sender-info" v-if="currentDetailMessage.sender">
                <img :src="currentDetailMessage.sender.avatar" class="sender-avatar" />
                <div class="sender-details">
                  <div class="sender-name">{{ currentDetailMessage.sender.name }}</div>
                  <div class="sender-dept">{{ currentDetailMessage.sender.department }}</div>
                </div>
              </div>
              <div class="message-time">{{ currentDetailMessage.time }}</div>
            </div>
            <div class="message-full-content">{{ currentDetailMessage.content }}</div>
          </div>
          <div class="modal-footer">
            <button class="btn-action" @click="navigateToPath(currentDetailMessage)">
              <i class="fas fa-external-link-alt"></i> 查看详情
            </button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { useStore } from 'vuex'
import { computed, ref, watch, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, SwipeCell, Dialog } from 'vant'
import api from '@/api'

export default {
  name: 'MessageDrawer',
  components: {
    SwipeCell,
  },
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { emit }) {
    const store = useStore()
    const router = useRouter()
    const activeTab = ref('all')
    const tabs = [
      { id: 'all', name: '全部' },
      { id: 'unread', name: '未读' },
      { id: 'todo', name: '待办' },
      { id: 'notice', name: '通知' }
    ]
    
    // 消息筛选
    const showFilter = ref(false)
    const filters = reactive({
      type: 'all',
      startDate: '',
      endDate: ''
    })
    
    const typeOptions = [
      { label: '全部', value: 'all' },
      { label: '待办', value: 'todo' },
      { label: '通知', value: 'notice' },
      { label: '流程', value: 'process' },
      { label: '公告', value: 'announcement' }
    ]
    
    // 高级搜索和筛选
    const showAdvancedSearch = ref(false)
    const searchFilters = reactive({
      type: [],
      dateRange: 'all'
    })
    
    // 日期选项
    const dateOptions = [
      { label: '全部时间', value: 'all' },
      { label: '今天', value: 'today' },
      { label: '本周', value: 'week' },
      { label: '本月', value: 'month' },
      { label: '本年', value: 'year' }
    ]
    
    // 排序选项
    const currentSort = ref('time')
    const sortOptions = [
      { label: '时间', value: 'time' },
      { label: '重要性', value: 'priority' }
    ]
    
    // 计算当前激活的筛选条件
    const activeFilters = computed(() => {
      const result = {}
      
      if (searchFilters.type.length > 0) {
        result.type = searchFilters.type
      }
      
      if (searchFilters.dateRange !== 'all') {
        result.dateRange = searchFilters.dateRange
      }
      
      return result
    })
    
    // 批量操作状态
    const batchMode = ref(false)
    const selectedMessages = ref([])
    const isAllSelected = computed(() => {
      return filteredMessages.value.length > 0 && 
             selectedMessages.value.length === filteredMessages.value.length
    })
    
    // 从store获取状态
    const loading = ref(false)
    const refreshing = ref(false)
    const hasError = ref(false)
    const errorMessage = ref('')
    const batchActionLoading = ref(false)
    const messages = computed(() => store.state.message.messages)
    const unreadCount = computed(() => store.state.message.unreadCount)
    
    // 滑动操作相关状态
    const swipeStates = ref([])
    const touchStartX = ref(0)
    const touchCurrentX = ref(0)
    const SWIPE_THRESHOLD = 80
    const swipeOffset = ref({})
    const showActions = ref({})
    
    // 消息详情状态
    const showMessageDetail = ref(false)
    const currentDetailMessage = ref({})
    
    // 消息列表本地状态
    const messageList = ref([])
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    })
    const filterParams = computed(() => {
      const params = {}
      if (filters.type !== 'all') params.type = filters.type
      if (filters.startDate) params.startDate = filters.startDate
      if (filters.endDate) params.endDate = filters.endDate
      return params
    })
    
    // 应用筛选条件后的消息列表
    const filteredMessages = computed(() => {
      let result = messages.value
      
      // 根据tab筛选
      if (activeTab.value !== 'all') {
        if (activeTab.value === 'unread') {
          result = result.filter(msg => !msg.read)
        } else {
          result = result.filter(msg => msg.type === activeTab.value)
        }
      }
      
      // 应用自定义筛选
      if (filters.type !== 'all') {
        result = result.filter(msg => msg.type === filters.type)
      }
      
      return result.map((msg, index) => {
        // 确保swipeStates数组有足够的元素
        if (!swipeStates.value[index]) {
          swipeStates.value[index] = { offset: 0, swiping: false }
        }
        return { ...msg, swiping: swipeStates.value[index].swiping }
      })
    })
    
    // 初始加载消息
    onMounted(() => {
      loadMessages()
      store.dispatch('message/fetchUnreadCount')
    })
    
    // 监听抽屉打开状态，打开时刷新消息
    watch(() => props.value, (newVal) => {
      if (newVal) {
        loadMessages()
        store.dispatch('message/fetchUnreadCount')
      }
    })
    
    // 加载消息列表
    const loadMessages = async (isRefresh = false) => {
      if (loading.value && !isRefresh) return
      if (isRefresh) {
        refreshing.value = true
      } else {
        loading.value = true
      }
      hasError.value = false
      
      try {
        const params = {
          page: isRefresh ? 1 : pagination.currentPage,
          limit: pagination.pageSize,
          type: activeTab.value,
          ...filterParams.value
        }
        
        const res = await api.message.getMessages(params)
        
        if (isRefresh) {
          messageList.value = res.data || []
          pagination.currentPage = 1
        } else {
          messageList.value = [...messageList.value, ...(res.data || [])]
          pagination.currentPage += 1
        }
        
        pagination.total = res.total || 0
        pagination.hasMore = messageList.value.length < pagination.total
        
        // 更新未读消息数量
        updateUnreadCount()
      } catch (error) {
        console.error('加载消息失败:', error)
        hasError.value = true
        errorMessage.value = error.message || '加载消息失败，请稍后重试'
        Toast.fail(errorMessage.value)
      } finally {
        loading.value = false
        refreshing.value = false
      }
    }
    
    // 刷新消息列表
    const refreshMessages = () => {
      return loadMessages(true)
    }
    
    // 更新未读消息数量
    const updateUnreadCount = async () => {
      try {
        const res = await api.message.getUnreadCount()
        store.commit('mobile/SET_UNREAD_COUNT', res.data || 0)
      } catch (error) {
        console.error('获取未读消息数量失败:', error)
      }
    }
    
    // 标记消息为已读
    const handleMarkRead = async (message) => {
      try {
        await api.message.markAsRead(message.id)
        // 更新本地消息状态
        const index = messageList.value.findIndex(msg => msg.id === message.id)
        if (index !== -1) {
          messageList.value[index].read = true
        }
        // 更新未读消息数量
        updateUnreadCount()
        Toast.success('已标记为已读')
      } catch (error) {
        console.error('标记消息已读失败:', error)
        Toast.fail('标记消息已读失败，请稍后重试')
      }
    }
    
    // 批量标记为已读
    const batchMarkRead = async () => {
      if (selectedMessages.value.length === 0) return
      
      batchActionLoading.value = true
      try {
        const messageIds = selectedMessages.value.map(msg => msg.id)
        await api.message.batchMarkAsRead(messageIds)
        
        // 更新本地消息状态
        messageList.value.forEach(msg => {
          if (messageIds.includes(msg.id)) {
            msg.read = true
          }
        })
        
        // 更新未读消息数量
        updateUnreadCount()
        
        // 清空选择
        selectedMessages.value = []
        
        Toast.success('批量标记已读成功')
      } catch (error) {
        console.error('批量标记已读失败:', error)
        Toast.fail('批量标记已读失败，请稍后重试')
      } finally {
        batchActionLoading.value = false
      }
    }
    
    // 删除消息
    const handleDelete = async (message) => {
      try {
        await api.message.deleteMessage(message.id)
        // 从列表中移除
        messageList.value = messageList.value.filter(msg => msg.id !== message.id)
        Toast.success('删除成功')
        // 如果删除的是未读消息，更新未读计数
        updateUnreadCount()
      } catch (error) {
        console.error('删除消息失败:', error)
        Toast.fail('删除消息失败，请稍后重试')
      }
    }
    
    // 查看消息详情
    const viewMessageDetail = async (message) => {
      currentDetailMessage.value = message
      showMessageDetail.value = true
      
      // 如果是未读消息，标记为已读
      if (!message.read) {
        handleMarkRead(message)
      }
      
      // 获取完整的消息详情
      try {
        const res = await api.message.getMessageDetail(message.id)
        if (res.data) {
          currentDetailMessage.value = { ...currentDetailMessage.value, ...res.data }
        }
      } catch (error) {
        console.error('获取消息详情失败:', error)
      }
    }
    
    // 处理消息点击事件
    const handleMessageClick = (message) => {
      // 显示消息详情
      viewMessageDetail(message)
    }
    
    // 关闭抽屉
    const closeDrawer = () => {
      emit('input', false)
      // 重置状态
      batchMode.value = false
      selectedMessages.value = []
      showFilter.value = false
    }
    
    // 导航到消息对应的页面
    const navigateToPath = (message) => {
      if (message.path) {
        closeMessageDetail()
        closeDrawer()
        router.push(message.path)
      }
    }
    
    // 关闭消息详情
    const closeMessageDetail = () => {
      showMessageDetail.value = false
    }
    
    // 标记所有消息为已读
    const handleMarkAllRead = async () => {
      Dialog.confirm({
        title: '全部已读',
        message: '确定要将所有消息标记为已读吗？',
      })
        .then(async () => {
          try {
            // 调用API标记所有消息为已读
            await api.message.markAllAsRead(activeTab.value !== 'all' ? activeTab.value : null)
            
            // 更新本地消息状态
            messageList.value.forEach(msg => {
              msg.read = true
            })
            
            // 更新未读消息数量
            updateUnreadCount()
            
            Toast.success('已全部标记为已读')
          } catch (error) {
            console.error('标记全部已读失败:', error)
            Toast.fail('操作失败，请稍后重试')
          }
        })
        .catch(() => {
          // 用户取消操作
        })
    }
    
    // 清空所有消息
    const handleClearMessages = async () => {
      Dialog.confirm({
        title: '清空消息',
        message: '确定要清空所有消息吗？此操作不可恢复！',
      })
        .then(async () => {
          try {
            // 获取当前显示的所有消息ID
            const messageIds = filteredMessages.value.map(msg => msg.id)
            
            if (messageIds.length === 0) {
              Toast('没有可清空的消息')
              return
            }
            
            // 调用批量删除API
            await api.message.batchDeleteMessages(messageIds)
            
            // 从本地消息列表中移除
            messageList.value = messageList.value.filter(msg => !messageIds.includes(msg.id))
            
            // 更新未读消息数量
            updateUnreadCount()
            
            Toast.success('消息已清空')
          } catch (error) {
            console.error('清空消息失败:', error)
            Toast.fail('操作失败，请稍后重试')
          }
        })
        .catch(() => {
          // 用户取消操作
        })
    }
    
    // 滑动手势处理方法
    const touchStart = (event, index) => {
      touchStartX.value = event.touches[0].clientX
      touchCurrentX.value = event.touches[0].clientX
    }
    
    const touchMove = (event, index) => {
      touchCurrentX.value = event.touches[0].clientX
      const diff = touchCurrentX.value - touchStartX.value
      
      // 限制最大滑动距离
      if (diff < 0 && diff > -150) {
        swipeOffset.value = {
          ...swipeOffset.value,
          [index]: diff
        }
      }
    }
    
    const touchEnd = (index) => {
      const offset = swipeOffset.value[index] || 0
      
      // 如果滑动距离足够，显示操作按钮
      if (offset < -50) {
        swipeOffset.value = {
          ...swipeOffset.value,
          [index]: -150
        }
        showActions.value = {
          ...showActions.value,
          [index]: true
        }
      } else {
        // 否则恢复原位
        swipeOffset.value = {
          ...swipeOffset.value,
          [index]: 0
        }
        showActions.value = {
          ...showActions.value,
          [index]: false
        }
      }
    }
    
    // 重置滑动状态
    const resetSwipe = (index) => {
      swipeOffset.value = {
        ...swipeOffset.value,
        [index]: 0
      }
      showActions.value = {
        ...showActions.value,
        [index]: false
      }
    }
    
    // 获取滑动样式
    const getSwipeStyle = (index) => {
      if (!swipeStates.value[index]) return {}
      return {
        transform: `translateX(${swipeOffset.value[index] || 0}px)`,
        transition: swipeStates.value[index].swiping ? 'none' : 'transform 0.3s'
      }
    }
    
    const getSwipeLeftStyle = (index) => {
      if (!swipeStates.value[index]) return {}
      const opacity = Math.min(Math.max(swipeOffset.value[index] / SWIPE_THRESHOLD, 0), 1)
      return {
        opacity: opacity,
        transition: swipeStates.value[index].swiping ? 'none' : 'opacity 0.3s'
      }
    }
    
    const getSwipeRightStyle = (index) => {
      if (!swipeStates.value[index]) return {}
      const opacity = Math.min(Math.max(-swipeOffset.value[index] / SWIPE_THRESHOLD, 0), 1)
      return {
        opacity: opacity,
        transition: swipeStates.value[index].swiping ? 'none' : 'opacity 0.3s'
      }
    }
    
    // 批量操作相关方法
    const toggleBatchMode = () => {
      batchMode.value = !batchMode.value
      if (!batchMode.value) {
        selectedMessages.value = []
      }
    }
    
    const isSelected = (id) => {
      return selectedMessages.value.includes(id)
    }
    
    const toggleSelect = (id) => {
      const index = selectedMessages.value.indexOf(id)
      if (index > -1) {
        selectedMessages.value.splice(index, 1)
      } else {
        selectedMessages.value.push(id)
      }
    }
    
    const toggleSelectAll = () => {
      if (isAllSelected.value) {
        selectedMessages.value = []
      } else {
        selectedMessages.value = filteredMessages.value.map(msg => msg.id)
      }
    }
    
    // 筛选相关方法
    const toggleFilterPanel = () => {
      showFilter.value = !showFilter.value
    }
    
    const setFilter = (key, value) => {
      filters[key] = value
    }
    
    const resetFilters = () => {
      Object.keys(filters).forEach(key => {
        filters[key] = 'all'
      })
    }
    
    const applyFilters = () => {
      showFilter.value = false
      // 筛选已经通过computed属性自动应用
    }
    
    // 批量删除消息
    const batchDelete = async () => {
      if (selectedMessages.value.length === 0) return
      
      Dialog.confirm({
        title: '确认删除',
        message: `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？`,
      })
        .then(async () => {
          batchActionLoading.value = true
          try {
            const messageIds = selectedMessages.value.map(msg => msg.id)
            await api.message.batchDeleteMessages(messageIds)
            
            // 从列表中移除
            messageList.value = messageList.value.filter(msg => !messageIds.includes(msg.id))
            
            // 更新未读消息数量
            updateUnreadCount()
            
            // 清空选择
            selectedMessages.value = []
            
            Toast.success('批量删除成功')
          } catch (error) {
            console.error('批量删除失败:', error)
            Toast.fail('批量删除失败，请稍后重试')
          } finally {
            batchActionLoading.value = false
          }
        })
        .catch(() => {
          // 取消删除
        })
    }
    
    // 获取指定类型的未读消息数量
    const getUnreadCount = (tabId) => {
      if (!messageList.value) return 0
      
      if (tabId === 'unread') {
        // 未读标签页直接返回所有未读消息数量
        return messageList.value.filter(msg => !msg.read).length
      } else if (tabId === 'all') {
        // 所有消息的未读数量
        return messageList.value.filter(msg => !msg.read).length
      } else {
        // 特定类型的未读消息数量
        return messageList.value.filter(msg => msg.type === tabId && !msg.read).length
      }
    }
    
    // 处理消息列表滚动事件
    const messageListRef = ref(null)
    const loadingMore = ref(false)
    const hasMore = computed(() => pagination.hasMore)
    
    const handleScroll = () => {
      if (!messageListRef.value || loading.value || !hasMore.value || loadingMore.value) return
      
      const scrollTop = messageListRef.value.scrollTop
      const scrollHeight = messageListRef.value.scrollHeight
      const clientHeight = messageListRef.value.clientHeight
      
      // 滚动到底部时加载更多
      if (scrollTop + clientHeight >= scrollHeight - 50) {
        loadingMore.value = true
        
        // 加载下一页数据
        loadMessages().finally(() => {
          loadingMore.value = false
        })
      }
    }
    
    // 根据消息类型获取对应的图标类名
    const getTypeIcon = (type) => {
      switch (type) {
        case 'todo':
          return 'fas fa-clipboard-check'
        case 'notice':
          return 'fas fa-bullhorn'
        case 'process':
          return 'fas fa-tasks'
        case 'announcement':
          return 'fas fa-newspaper'
        default:
          return 'fas fa-bell'
      }
    }
    
    // 根据消息类型获取对应的颜色
    const getTypeColor = (type) => {
      switch (type) {
        case 'todo':
          return '#1890ff' // 蓝色
        case 'notice':
          return '#52c41a' // 绿色
        case 'process':
          return '#722ed1' // 紫色
        case 'announcement':
          return '#fa8c16' // 橙色
        default:
          return '#bfbfbf' // 灰色
      }
    }
    
    // 切换高级搜索面板
    const toggleAdvancedSearch = () => {
      showAdvancedSearch.value = !showAdvancedSearch.value
    }
    
    // 切换筛选选项
    const toggleFilterOption = (key, value) => {
      if (key === 'type') {
        const index = searchFilters.type.indexOf(value)
        if (index > -1) {
          searchFilters.type.splice(index, 1)
        } else {
          searchFilters.type.push(value)
        }
      } else {
        searchFilters[key] = value
      }
    }
    
    // 检查筛选选项是否被选中
    const isFilterSelected = (key, value) => {
      if (key === 'type') {
        return searchFilters.type.includes(value)
      }
      return searchFilters[key] === value
    }
    
    // 重置所有筛选条件
    const resetSearchFilters = () => {
      searchFilters.type = []
      searchFilters.dateRange = 'all'
    }
    
    // 应用筛选条件
    const applySearchFilters = () => {
      showAdvancedSearch.value = false
      // 刷新消息列表
      refreshMessages()
    }
    
    // 移除筛选条件
    const removeFilter = (key) => {
      if (key === 'type') {
        searchFilters.type = []
      } else {
        searchFilters[key] = key === 'dateRange' ? 'all' : ''
      }
      refreshMessages()
    }
    
    // 获取筛选标签显示文本
    const getFilterLabel = (key, value) => {
      if (key === 'type') {
        const typeNames = value.map(t => typeOptions.find(option => option.value === t)?.label || t)
        return `类型: ${typeNames.join(', ')}`
      } else if (key === 'dateRange') {
        const dateOption = dateOptions.find(option => option.value === value)
        return `时间: ${dateOption?.label || value}`
      }
      return `${key}: ${value}`
    }
    
    // 设置排序选项
    const setSortOption = (value) => {
      currentSort.value = value
      refreshMessages()
    }
    
    // 获取排序图标
    const getSortIcon = (value) => {
      if (currentSort.value !== value) return ''
      return 'fas fa-check'
    }
    
    return {
      activeTab,
      tabs,
      loading,
      refreshing,
      hasError,
      errorMessage,
      batchActionLoading,
      filteredMessages,
      closeDrawer,
      handleMessageClick,
      deleteMessage,
      markAsRead,
      handleMarkAllRead,
      handleClearMessages,
      getUnreadCount,
      getTypeIcon,
      getTypeColor,
      
      // 滑动操作
      touchStart,
      touchMove,
      touchEnd,
      getSwipeStyle,
      getSwipeLeftStyle,
      getSwipeRightStyle,
      
      // 批量操作
      batchMode,
      toggleBatchMode,
      isSelected,
      toggleSelect,
      isAllSelected,
      toggleSelectAll,
      batchMarkRead,
      batchDelete,
      selectedMessages,
      
      // 筛选
      showFilter,
      filters,
      typeOptions,
      toggleFilterPanel,
      resetFilters,
      applyFilters,
      
      // 消息详情
      showMessageDetail,
      currentDetailMessage,
      closeMessageDetail,
      navigateToPath,
      
      // 加载消息列表
      loadMessages,
      refreshMessages,
      updateUnreadCount,
      
      // 加载消息列表
      messageList,
      pagination,
      filterParams,
      
      // 加载消息列表
      viewMessageDetail,
      
      // 处理消息列表滚动事件
      messageListRef,
      loadingMore,
      hasMore,
      handleScroll,
      
      // 高级搜索和筛选
      showAdvancedSearch,
      searchFilters,
      dateOptions,
      currentSort,
      sortOptions,
      activeFilters,
      toggleAdvancedSearch,
      toggleFilterOption,
      isFilterSelected,
      setFilter,
      resetSearchFilters,
      applySearchFilters,
      removeFilter,
      getFilterLabel,
      setSortOption,
      getSortIcon,
      swipeOffset,
      showActions,
      handleMarkRead,
      handleDelete
    }
  }
}
</script>

<style scoped>
.message-drawer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  visibility: hidden;
  transition: visibility 0.3s;
}

.message-drawer.open {
  visibility: visible;
}

.drawer-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.open .drawer-mask {
  opacity: 1;
}

.drawer-content {
  position: absolute;
  top: 0;
  right: 0;
  width: 90%;
  max-width: 400px;
  height: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  transform: translateX(100%);
  transition: transform 0.3s;
}

.open .drawer-content {
  transform: translateX(0);
}

.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-title {
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
}

.batch-mode-toggle {
  margin-right: 16px;
  font-size: 14px;
  color: #1890ff;
}

.drawer-close {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.message-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.message-tab {
  flex: 1;
  padding: 12px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  position: relative;
}

.message-tab.active {
  color: #1890ff;
  font-weight: 500;
}

.message-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 2px;
  background-color: #1890ff;
}

.tab-badge {
  display: inline-block;
  background-color: #f5222d;
  color: white;
  border-radius: 10px;
  min-width: 16px;
  height: 16px;
  font-size: 12px;
  line-height: 16px;
  text-align: center;
  padding: 0 4px;
  margin-left: 4px;
}

/* 批量操作样式 */
.batch-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #f9f9f9;
}

.select-all {
  display: flex;
  align-items: center;
  color: #666;
}

.select-all i {
  margin-right: 4px;
  color: #1890ff;
}

.batch-action-btns {
  display: flex;
}

.batch-action-btns button {
  background: none;
  border: none;
  padding: 6px 10px;
  margin-left: 8px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
}

.btn-read {
  color: #1890ff;
}

.btn-delete {
  color: #f5222d;
}

/* 筛选面板样式 */
.search-filters {
  position: relative;
  border-bottom: 1px solid #f0f0f0;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 16px;
}

.filter-tag {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
  background-color: #fff;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
}

.filter-tag i {
  margin-left: 4px;
}

.filter-button {
  position: absolute;
  top: 12px;
  right: 16px;
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
  background-color: #fff;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
}

.filter-button i {
  margin-right: 4px;
}

.advanced-search-panel {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background-color: #f9f9f9;
}

.filter-group {
  margin-bottom: 16px;
}

.filter-label {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-checkbox {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
  background-color: #fff;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
}

.filter-checkbox i {
  margin-right: 4px;
}

.filter-checkbox.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.date-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.date-option {
  padding: 6px 12px;
  border-radius: 4px;
  background-color: #fff;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
}

.date-option.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.filter-actions button {
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
}

.btn-reset {
  margin-right: 8px;
  background-color: #fff;
  color: #666;
}

.btn-apply {
  background-color: #1890ff;
  color: #fff;
  border-color: #1890ff;
}

/* 消息列表样式 */
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.swipe-container {
  position: relative;
  overflow: hidden;
  margin-bottom: 1px;
}

.message-item {
  position: relative;
  transition: transform 0.3s ease;
  z-index: 2;
}

.message-item.deleting {
  transform: translateX(-100%);
  opacity: 0;
  height: 0;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.message-item.read {
  background-color: #f9f9f9;
}

.message-item.unread {
  background-color: #e6f7ff;
}

.select-box {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
  color: #666;
}

.message-item.selected .select-box {
  color: #1890ff;
}

.swipe-action {
  position: absolute;
  top: 0;
  height: 100%;
  display: flex;
  align-items: center;
}

.swipe-action.left {
  left: 0;
  justify-content: flex-end;
}

.swipe-action.right {
  right: 0;
  justify-content: flex-start;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 100%;
  color: white;
  font-size: 13px;
}

.action-btn i {
  font-size: 16px;
  margin-bottom: 4px;
}

.read-btn {
  background-color: #1890ff;
}

.delete-btn {
  background-color: #f5222d;
}

.message-content {
  flex: 1;
  display: flex;
  padding: 12px 16px;
  background-color: #fff;
}

.message-item.unread .message-content {
  background-color: #e6f7ff;
}

.message-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
  flex-shrink: 0;
}

.message-body {
  flex: 1;
  min-width: 0;
}

.message-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.message-detail {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.loading-message,
.empty-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #999;
}

.loading-message i,
.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.empty-text {
  font-size: 14px;
}

.drawer-footer {
  display: flex;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
}

.footer-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 0;
  color: #1890ff;
  font-size: 14px;
}

.footer-btn.danger {
  color: #f5222d;
}

/* 消息详情弹窗样式 */
.message-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1100;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  width: 90%;
  max-width: 500px;
  max-height: 90%;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-icon {
  font-size: 16px;
  color: #999;
  cursor: pointer;
}

.modal-body {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.message-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.sender-info {
  display: flex;
  align-items: center;
}

.sender-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
}

.sender-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.sender-dept {
  font-size: 12px;
  color: #999;
}

.message-full-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.modal-footer {
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
}

.modal-footer button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  background-color: #1890ff;
  color: #fff;
  border: none;
}

/* 动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.read-indicator {
  transition: background-color 0.3s;
}

.retry-btn {
  margin-top: 12px;
  color: #1890ff;
  font-size: 14px;
  padding: 6px 12px;
  border: 1px solid #1890ff;
  border-radius: 4px;
  cursor: pointer;
}

.batch-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  z-index: 101;
  padding-bottom: env(safe-area-inset-bottom);
}

.select-all-btn {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.select-all-btn i {
  margin-right: 8px;
  font-size: 18px;
  color: #1890ff;
}

.action-buttons {
  display: flex;
  height: 50px;
}

.action-buttons .action-btn {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  color: #fff;
  height: 100%;
}

.action-buttons .action-btn i {
  margin-right: 4px;
  margin-bottom: 0;
}

.action-buttons .action-btn.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.mark-read-btn {
  background-color: #1890ff;
}

/* 滑动操作相关样式 */
.swipe-container {
  position: relative;
  overflow: hidden;
  margin-bottom: 1px;
}

.message-item {
  position: relative;
  transition: transform 0.3s ease;
  z-index: 2;
}

.action-buttons-container {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  display: flex;
  align-items: center;
  z-index: 1;
}

.action-buttons-container .action-btn {
  width: 75px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 13px;
}

.action-buttons-container .action-btn.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.mark-read-btn {
  background-color: #1890ff;
}
</style> 